import Cookies from "js-cookie";
import { App } from "vue";
import type { RouteRecordRaw } from "vue-router";
import { createRouter, createWebHashHistory } from "vue-router";
import { useUserStoreWithOut } from "@/store/modules/user";
import * as http from "@/request/api";
const userStore = useUserStoreWithOut();
const routes: RouteRecordRaw[] = [
  {
    path: "/login",
    name: "login",
    component: () => import("../views/Login/index.vue"),
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach(async (to, from, next) => {
  // token存在 && pinia没有menus(重新获取用户信息)
  const token = Cookies.get("token");
  console.log(token);
  if (token && userStore.menus.length === 0) {
    // 重新获取
    let userinfo = await http.admin.getAdminInfo();
    if (userinfo.code === 200) {
      // 存储到pinia-更新
      userStore.updateMenus(userinfo.data.menus);
      // 获取getter
      const newMenus = userStore.genMenuConf;
      console.log(newMenus);
      // 生成路由规则
      // const newRouters: RouteRecordRaw[] = [];
      for (let key in newMenus) {
        let newRouters: RouteRecordRaw = {
          path: "/" + newMenus[key].name,
          name: newMenus[key].name,
          component: () => import("@/views/Home/index.vue"),
          children: [],
        };
        // console.log(newRouters);
        newMenus[key].children?.forEach((submenus) => {
          newRouters.children!.push({
            path: submenus.name,
            name: submenus.name,
            component: () =>
              import(`@/views/${newMenus[key].name}/${submenus.name}.vue`),
          });
        });
        router.addRoute(newRouters);
      }
      // 动态路由跳转到首页
      router.addRoute({
        path: "/",
        name: "home",
        redirect: "/index",
        component: () => import("@/views/Home/index.vue"),
        children: [
          {
            path: "index",
            name: "index",
            component: () => import("@/views/index/index.vue"),
          },
        ],
      });
      return next(to);
    } else {
      Cookies.remove("token");
      return next("/login");
    }
  } else if (!token && to.path !== "/login") {
    return next("/login");
  } else if (token && to.path === "/login") {
    return next(from);
  } else {
    next();
  }
});
// 初始化方法
export const initRouter = (app: App<Element>) => {
  app.use(router);
};
